/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia.model;

import br.com.jr2tecnologia.LoggerFactory;
import br.com.jr2tecnologia.model.entity.ClientPhone;
import br.com.jr2tecnologia.model.entity.Company;
import br.com.jr2tecnologia.model.persistence.DAOException;
import br.com.jr2tecnologia.model.persistence.DAOFactory;
import br.com.jr2tecnologia.model.repository.ClientPhoneRepository;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author ronildo
 */

@Stateless
public class ClientPhonePersistence implements ClientPhonePersistenceLocal{

    private static final Logger logger = LoggerFactory.getLogger();

    @PersistenceContext
    private EntityManager em;
    private ClientPhoneRepository clientPhoneRepository;

    @PostConstruct
    public void initialize(){
        clientPhoneRepository = DAOFactory.getClientPhoneRepository(em);
    }

    public void persist(ClientPhone clientPhone){
        clientPhoneRepository.persist(clientPhone);
    }

    public void update(ClientPhone clientPhone){
        clientPhoneRepository.update(clientPhone);
    }

    public void remove(ClientPhone clientPhone){
        clientPhoneRepository.remove(clientPhone, clientPhone.getPkClientPhone());
    }

    public ClientPhone findByPhone(String phone){
        try{
            return clientPhoneRepository.findByPhone(phone);
        }catch(DAOException e){
            logger.severe("canot list clientPhone");
            return null;
        }
    }

    public ClientPhone findByPhone(Company company, String phone){
        try{
            ClientPhone clientPhone = new ClientPhone();
            clientPhone.setCompany(company);
            clientPhone.setPhone(phone);
            List<ClientPhone> list = clientPhoneRepository.list(clientPhone);
            if(list.size() > 1)
                throw new PersistenceUnitException("Have more than one result");
            else if(list.size() == 0){
                logger.info("Cannot find data ClientPhone by phone: " + phone);
                return null;
            }
            else
                return list.get(0);
        }catch(DAOException e){
            logger.severe("canot list clientPhone");
            return null;
        }
    }

    public List<ClientPhone> list(ClientPhone clientPhone){
        try{
            return clientPhoneRepository.list(clientPhone);
        }catch(DAOException e){
            logger.severe("canot list clientPhone");
            return null;
        }
    }

    public List<ClientPhone> listAll(){
        try{
            return clientPhoneRepository.listAll();
        }catch(DAOException e){
            logger.severe("canot list clientPhone");
            return null;
        }
    }

}
